package noinfuse;

import util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 通过PreparedStatement占位符，防止sql注入
 */
public class GuardSql {
    /**
     * 根据id查询代理协议
     * @param id
     */
    public static void selectAgentById(String id){
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Connection connection = null;
        try {
            //获取数据库连接对象
            connection = JDBCUtil.connect();
            //预编译sql，不执行，使用？作为占位符
            String sql = "select * from agent where id = ? ";
            preparedStatement = connection.prepareStatement(sql);
            //手动给参数赋值
            preparedStatement.setString(1,id);
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                System.out.println("id:" + resultSet.getObject("id"));
                System.out.println("agent_num:" + resultSet.getObject("agent_num"));
                System.out.println("agent_name:" + resultSet.getObject("agent_name"));
                System.out.println("create_time:" + resultSet.getObject("create_time"));
                System.out.println("---------------------------------------------------------");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.closeResource(resultSet, null, connection);
        }
    }

    public static void main(String[] args) {
        //不正常调用，自定义拼接sql，但是通过PreparedStatement的占位符还是只能查出来一条数据
        GuardSql.selectAgentById("1 or 1 = 1");
    }
}
